package com.aiyige.page.my.wallet.dialog;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.HandlerUtil;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.model.User;
import com.aiyige.model.request.WithdrawModel;
import com.aiyige.model.response.BaseResponse;
import com.aiyige.page.my.order.dialog.ClassifyAdapter;
import com.aiyige.page.my.order.dialog.OrderTimeAdapter;
import com.aiyige.page.my.order.model.SubjectSelection;
import com.aiyige.page.my.order.model.TimeSelectionEntity;
import com.aiyige.page.my.wallet.model.WithdrawResp;
import com.aiyige.page.my.wallet.utils.WalletServiceModel;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.BaseBottomDialogFragment;
import com.aiyige.utils.widget.PayPwdEditText;
import com.aiyige.utils.widget.autoLayoutManager.AutoLayoutManager;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.vondear.rxtools.RxKeyboardTool;
import com.vondear.rxtools.RxTool;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 验证钱包密码dialog
 */
public class VerifyWalletPwdDialog extends BaseBottomDialogFragment {

    Unbinder unbinder;

    public static VerifyWalletPwdDialog newInstance() {
        return new VerifyWalletPwdDialog();
    }

    @BindView(R.id.pay_pwd_edittext)
    PayPwdEditText payPwdEdittext;

    @BindView(R.id.rl_verifying)
    RelativeLayout rlVerifying;

    @BindView(R.id.iv_loading)
    ImageView tvLoading;

    Listener listener;

    public void setLisenter(Listener callback) {
        this.listener = callback;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_verify_wallet_pwd, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        /**
         * @param bgdrawable 背景drawable
         * @param pwdlength 密码长度
         * @param splilinewidth 分割线宽度
         * @param splilinecolor 分割线颜色
         * @param pwdcolor 密码字体颜色
         * @param pwdsize 密码字体大小
         */
        payPwdEdittext.initStyle(R.drawable.edit_num_bg, 6, 0.5f, R.color.zwcolor_gray_bfbfbf, R.color.zwcolor_black_111111, 32);
        payPwdEdittext.setOnTextFinishListener(new PayPwdEditText.OnTextFinishListener() {
            @Override
            public void onFinish(String str) {//密码输入完后的回调
                requestWithdraw();
            }
        });
        // 解决dilaog中EditText无法弹出输入的问题
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        //弹出对话框后直接弹出键盘
        payPwdEdittext.getEditText().setFocusableInTouchMode(true);
        payPwdEdittext.getEditText().requestFocus();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputManager =(InputMethodManager) payPwdEdittext.getEditText().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(payPwdEdittext.getEditText(), 0);
            }
        }, 100);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void show(FragmentManager manager, String tag) {
        super.show(manager, tag);

    }

    @OnClick({R.id.iv_close, R.id.tv_setpwd_hint})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.tv_setpwd_hint:
                dismiss();
                ARouter.getInstance()
                        .build(ARouterConfig.WalletVerifyCodePage)
                        .navigation();
                break;
        }
    }

    public interface Listener {
        void onWithdrawalFinish();

        String getAccount();

        String getName();

        double getAmount();

    }

    private String getPassword() {
        return payPwdEdittext.getPwdText();
    }

    private void requestWithdraw() {
        if (listener == null) {
            return;
        }
        if (TextUtils.isEmpty(getPassword())) {
            ToastX.show(R.string.password_empty);
            return;
        }
        rlVerifying.setVisibility(View.VISIBLE);
        GlideUtil.with(getContext()).loadGif(tvLoading, R.drawable.withdrawal_load_gif, 0);
        WithdrawModel model = WithdrawModel.newBuilder().account(listener.getAccount()).name(listener.getName()).amount(listener.getAmount()).password(RxTool.Md5(getPassword())).actionTime(System.currentTimeMillis()).build();
        ApiManager.getService().withdraw(model).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (!response.isSuccessful()) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    } else {
                        GlideUtil.with(getContext()).loadGif(tvLoading, R.drawable.withdrawal_finish_gif, 1);
                        String json = RetrofitUtil.getResponseBodyAsString(response);
                        WithdrawResp withdrawResp = JSON.parseObject(json, WithdrawResp.class);
                        User user = AccountUtil.getCurrentUser();
                        user.getStatisticsBackup().setPurseBalance(withdrawResp.getPurseBalance());
                        AccountUtil.updateCurrentUser(user);
                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (listener != null) {
                                    listener.onWithdrawalFinish();
                                }
                            }
                        }, 1000);
                    }
                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                ToastX.show(t.getMessage());
                dismiss();
            }
        });

    }
}
